class FiveChessPlayScene extends eui.Component implements eui.UIComponent {

	public boardGroup: eui.Group;
	public peiceGroup: eui.Group;

	public backBtn: eui.Button;
	public homeBtn: eui.Button;
	public huiqiBtn: eui.Button;
	public restartBtn: eui.Button;
	public soundBtn: eui.Button;

	public player1: eui.Group;
	public player2: eui.Group;
	public msgLabel: eui.Label;

	public playGroup: eui.Group;
	public preBtn: eui.Button;
	public afterBtn: eui.Button;

	public gameSelectGroup: eui.Group;
	public selfPeice: eui.Image;
	public selfPeiceTypeList: eui.List;
	public levelTypeList: eui.List;

	private chessBoard: chess.ChessBoard;
	/** 负极值搜索算法 */
	private negaMaxSearch: ai.NegaMaxSearch;
	/** 棋子的落子顺序可以用来悔棋 */
	private _peiceArray: Array<any> = [];
	/** 最后一手的谁下的 */
	private _lastRole: number = 0;
	/**是否结束 */
	private _isEnd: boolean = true;
	/** 1：人机，2:人人 */
	private _gameType: number;
	/** 是否先手,默认人优先 */
	private _firstRole: number = chess.ChessConst.role.hum;


	public pecieTypeListData = [{ type: 1, text: "执黑" }, { type: 0, text: "执白" }];
	public levelListData = [{ type: 4, text: "低级" }, { type: 6, text: "中级" }, { type: 8, text: "高级" }];

	public constructor() {
		super();
		let self = this;
		self.addEventListener(egret.Event.ADDED_TO_STAGE, self.onAdd, self);
		self.addEventListener(egret.Event.REMOVED_FROM_STAGE, this.onRemove, self);
		self.chessBoard = new chess.ChessBoard();
		self.negaMaxSearch = new ai.NegaMaxSearch();
		self.negaMaxSearch.board = this.chessBoard;
	}

	protected partAdded(partName: string, instance: any): void {
		super.partAdded(partName, instance);
	}

	public setData(data) {
		this._gameType = data;
	}


	protected childrenCreated(): void {
		let self = this;
		super.childrenCreated();
		self.peiceGroup.touchChildren = false;
		self.selfPeiceTypeList.itemRenderer = CommonListItem;
		self.levelTypeList.itemRenderer = CommonListItem;
		self.selfPeiceTypeList.dataProvider = new eui.ArrayCollection(this.pecieTypeListData);
		self.levelTypeList.dataProvider = new eui.ArrayCollection(this.levelListData);
		self.selfPeiceTypeList.selectedIndex = 0;
		self.levelTypeList.selectedIndex = 0;
		this.setGameSelect();
	}

	private onAdd(e: egret.Event) {
		this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick, this);
		this.selfPeiceTypeList.addEventListener(egret.Event.CHANGE, this.onChangePeiceType, this);
		this.boardGroup.addEventListener(egret.TouchEvent.TOUCH_TAP, this.clickBoard, this)

	}

	private onRemove(e: egret.Event) {
		this.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick, this);
		this.boardGroup.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.clickBoard, this)
		this.selfPeiceTypeList.removeEventListener(egret.Event.CHANGE, this.onChangePeiceType, this);
	}

	private onClick(e: egret.TouchEvent) {
		let self = this;
		let target = e.target;
		switch (target) {
			case self.restartBtn:
				self.setGameSelect();
				break;
			case self.selfPeice:
				self.startGame();
				break;
			case self.huiqiBtn:
				self.huiqi();
				break;
		}
	}

	private clickBoard(e: egret.TouchEvent) {
		let self = this;
		if (self._isEnd) {
			this.msgLabel.text = "请点击重来";
			return;
		} else if (self._lastRole == chess.ChessConst.role.hum || (self._lastRole == 0 && self._firstRole != chess.ChessConst.role.hum)) {
			this.msgLabel.text = "等待对方落子";
			return;
		}
		let x = e.localX;
		let y = e.localY;
		if (-20 > x || x > 620 || -20 > y || y > 620) return;
		//判断该点离在方格的4个区域中的哪个
		let positionX = Math.round(x / 40);
		let positionY = Math.round(y / 40);
		positionX = positionX <= 0 ? 0 : positionX;
		positionY = positionY <= 0 ? 0 : positionY;
		if (self.chessBoard.board[positionX][positionY] != 0) {
			self.msgLabel.text = "请选择空白区域落子";
			return;
		}
		self.putPeice(positionX, positionY);
		if (self._gameType == 1) { egret.setTimeout(() => { self.aiPutPeice(); }, this, 100); }
		e.stopImmediatePropagation();
	}

	/** 落子 */
	public putPeice(positionX, positionY) {
		let self = this;
		if (self._isEnd) return;
		//执黑先行
		if (self._lastRole == 0) self._lastRole = self._firstRole;
		else this._lastRole = chess.ChessConst.role.reverse(self._lastRole);
		let peiceType = (self._peiceArray.length + 1) % 2;
		let peice = new PeiceItem(positionX, positionY, peiceType);
		// let peice = new ChessPeice(positionX, positionY, peiceType, 20);
		self._peiceArray.push(peice);
		this.chessBoard.put([positionX, positionY], self._lastRole);
		self.peiceGroup.addChild(peice);
		self.msgLabel.text = chess.ChessConst.roleName[peiceType] + `落子[${positionX},${positionY}]`;
		if (ai.WinUtils.getInstance().isFive(self.chessBoard.board, [positionX, positionY], this._lastRole)) {
			self.msgLabel.text = chess.ChessConst.roleName[peiceType] + "获胜";
			self._isEnd = true;
		}
	}

	/** ai落子 */
	private aiPutPeice() {
		let p, self = this;
		if (self._isEnd) return;
		if (self.chessBoard.allSteps.length > 1) p = ai.Opening.getInstance().match(self.chessBoard);
		p = p || this.negaMaxSearch.deepAll(undefined, chess.ChessConst.config.searchDeep);
		self.chessBoard.put(p, chess.ChessConst.role.com);
		self.putPeice(p[0], p[1]);
	}


	private setGameSelect() {
		let self = this;
		self.initChessData();
		self.chessBoard.init(15);
		self.gameSelectGroup.visible = true;
	}

	private startGame() {
		let self = this;
		chess.ChessConst.config.searchDeep = self.levelTypeList.selectedItem.type;
		self.gameSelectGroup.visible = false;
		self._isEnd = false;
		if (self.selfPeiceTypeList.selectedItem.type == 1) self._firstRole = chess.ChessConst.role.hum;
		else { //对方先行
			self._firstRole = chess.ChessConst.role.com;
			if (self._gameType == 1) self.putPeice(7, 7);
		}
	}

	/** 悔棋 */
	private huiqi() {
		if (this._isEnd) return;
		this.chessBoard.backward();
		let i = 0;
		while (i < 2) {
			let s = this._peiceArray.pop();
			this.peiceGroup.removeChild(s);
			i++
		}
	}

	public updateChessBoard() {
		let self = this;
		let board = self.chessBoard.board;
		for (let i = 0; i < board.length; i++) {
			for (let j = 0; j < board[i].length; j++) {
			}
		}
	}

	private onChangePeiceType(e: egret.Event) {
		let item = this.selfPeiceTypeList.selectedItem;
		this.selfPeice.source = "peice_" + item.type + "_png"
	}

	private initChessData() {
		let self = this;
		while (self._peiceArray.length) {
			let peice = self._peiceArray.shift();
			self.peiceGroup.removeChild(peice);
		}
		self._lastRole = 0;
		self.msgLabel.text = "游戏信息";
	}
}